var username;
var userGist;
var userGistUrl;

var trashGist;
var trashGistUrl;

var loginGist = "988d0e359083d3cc29fdc817b2667973";
var loginGistUrl = "https://api.github.com/gists/" + loginGist + "/comments";

var accessToken = "token 5d6259a23fc24eb956a4309ea48db8364afa249d";

var tagList = [];

function paddingZero(num, n) {

    var str = String(num),
        len = str.length;

    for (var i = len; i < n; i++) {
        str = '0' + str;
    }

    return str;
}

function dispalyLinkAccordingTagList() {

    $("#linkers li").each(function () {

        var display = true;
        for (var i = 0, len = tagList.length; i < len; i++) {
            if (!($(this).hasClass(tagList[i]))) {
                display = false;
                break;
            }
        }
        
        if (display === true) {
            $(this).css("display", "block");
        }
    });
}

function getLinkers() {

    $("#linkers").html("");

    $.ajax({
        type: "get",
        url: userGistUrl,
        headers: {
            Authorization: accessToken
        }, 
        success: function (data, status) {

            var len = data.length,
                n = String(len).length,
                commentsID = [],
                attributeList;

            if (n < 3) n = 3;

            for (var i = 0, len = data.length; i < len; i++) {

                commentsID.push(data[len-i-1].id);
                attributeList = [];

                var body = JSON.parse(data[len-i-1].body);
                var url = body.link;
                var tags = body.tags.split(',');
                var tagContent = '';
                for (var j = 0, l = tags.length; j < l; j++) {
                    tagContent += '<a href="#">' + tags[j].trim() + '</a>';
                    attributeList.push(tags[j]);
                }

                $("#linkers").append(
                    '<li class="' + attributeList.join(' ') + '">' +
                        '<div class="link">' + 
                            '<span>#' + paddingZero(i + 1, n) + '</span>' + 
                            '<a href="' + url + '">' + url + '</a>' +
                            '<span class="delete">x</span>' +
                            '<span class="clicknum">1</span>' +
                        '</div>' +
                        '<div class="tags">' + 
                            tagContent + 
                        '</div>' + 
                    '</li>'
                );
            }

            $("#linkers .delete").each(function (index) {
                $(this).click(function () {
                    deleteLinker(index, commentsID[index]);
                })
            });

            $(".tags a").click(function () {

                var tagName = $(this).text();

                if (tagList.indexOf(tagName) == -1) {

                    tagList.push(tagName);
                    $("#linkers li").not('.' + tagName).css("display", "none");

                    $("#taglist").append(
                        '<li>' + tagName + '<span class="delete">x</span></li>' 
                    );

                    $("#taglist li").click(function() {
                        var pos = tagList.indexOf(tagName);
                        tagList.splice(pos, 1);
                        $(this).remove();
                        dispalyLinkAccordingTagList();
                    });
                }
            });
        }
    });
}

function addLinker() {

    var content = {
        link: $("#link").val(),
        tags: $("#tag").val()
    };

    var body = {
        body: JSON.stringify(content)
    };

    $.ajax({
        type: "post",
        url: userGistUrl, 
        headers: {
            Authorization: accessToken
        },
        dataType: "json",
        data: JSON.stringify(body),
        success: function (data, status) {
            $("#link").val("");
            $("#tag").val("");
            getLinkers();
        }
    });
}

function deleteLinker(index, id) {

    // get the link for userGist
    $.get(userGistUrl + "/" + id, function (data, status) {

        console.log(data.body);

        var body = {
            body: data.body
        };

        // post the link to trashGist
        $.ajax({
            type: "post",
            url: trashGistUrl,
            headers: {
                Authorization: accessToken
            },
            dataType: "json",
            data: JSON.stringify(body),
            success: function (data, status) {

                // delete the link from userGist
                $.ajax({
                    type: "delete",
                    url: userGistUrl + "/" + id,
                    headers: {
                        Authorization: accessToken
                    },
                    success: function (data, status) {
                        $("#linkers li").eq(index).remove();
                    }
                });
            }
        });
    });
}

function logined() {

    $("#username").val("");
    $("#login").css("display", "none");
    $("#display").css("display", "block");

    // display login info
    $("#logout").html(
        'Hello, <span>' + username + '</span><a href="#">[logout]</a>'
    ).css("display", "block");

    // logout
    $("#logout a").click(function() {
        localStorage.removeItem("linkerUserInfo");
        $("#login").css("display", "block");
        $("#display").css("display", "none");
        $("#logout").css("display", "none");
    });
    
    getLinkers();

    $("#addLink").click(function() {
        $("#addLink").css("display", "none");
        $("#editor").css("display", "block");
    });

    $("#confirm").click(function() {
        $("#editor").css("display", "none");
        $("#addLink").css("display", "inline-block");
        addLinker();
        $("#link").val("");
        $("#tag").val("");
    });

    $("#cancel").click(function() {
        $("#editor").css("display", "none");
        $("#addLink").css("display", "inline-block");
        $("#link").val("");
        $("#tag").val("");
    });
}

function matchUser(user) {

    if (user.name == username) {

        userGist = user.id;
        userGistUrl = "https://api.github.com/gists/" + userGist + "/comments";
                
        trashGist = user.trash;
        trashGistUrl = "https://api.github.com/gists/" + trashGist + "/comments";
        
        return true;
    }

    return false;

}

$(document).ready(function () {

    // get information from localStorage

    if (localStorage.linkerUserInfo) {

        var user = JSON.parse(localStorage.linkerUserInfo);

        username = user.name;

        matchUser(user);

        logined();
    
    } else {
    
        // display the login window

        $("#login").css("display", "block");
    
    }

    $("#loginBtn").click(function() {

        var found = false;

        username = $("#username").val()

        // if can't find from localStorage, you need to fetch info from gist

        if (found === false) {

            $.ajax({
                type: 'get',
                url: loginGistUrl,
                headers: {
                    Authorization: accessToken
                },
                success: function (data, status) {

                    for (var i = 0, len = data.length; i < len; i++) {
                        var user = JSON.parse(data[i].body);
                        if (matchUser(user)) {
                            localStorage.setItem("linkerUserInfo", data[i].body);
                            found = true;
                            break;
                        }
                    }

                    if (found === false) {
                        alert("you are not invited!");
                    } else {
                        logined();
                    }
                }
            });
        }

    });
});
